//index.js
const app = getApp()
const db = wx.cloud.database();
let   request = null
Page({
  data: {

  },

  onLoad(query) {
    this.onGetOpenid();
  

  },

  getUserProfile(e) {
 
    wx.getUserProfile({
      desc: '获取微信用户信息', // 
      success: (res) => {
        app.globalData.userInfo = res.userInfo
        console.log(app.globalData)
        if (request.length) {
          console.log("用户已经绑定")
          wx.navigateTo({
            url: '../tabs/tabs',//跳转到个人中心页面
          })
        }
        else{
        console.log("用户没有绑定")
        wx.navigateTo({
          url: '../select/select',//跳转到绑定账户页面
        })
        }


      }
    })
  },
  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData.openid = res.result.openid
        console.log(app.globalData)
        console.log('[云函数] [login] user openid: ', app.globalData.openid)
        this.isBind()

      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  // 判断用户是否绑定过
  isBind(){

    db.collection("teacher_users").where({
      openid:app.globalData.openid
    }).get().then(res => {
      request = res.data
      console.log(request)
      if (!request.length) {
        db.collection("users").where({
          openid:app.globalData.openid
        }).get().then(res => {
          request = res.data
          console.log(request)
          if (request.length) {
            app.globalData.isStudent = '1'
          }
        })
      }
      else{
        app.globalData.isStudent = '0'
        console.log('else执行')
        console.log(app.globalData)
      }
    })
  }

  // 将用户信息写入数据库

})
